<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item class="breadcrumb_active_item"
            >成绩查询</el-breadcrumb-item
          >
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="results_list_content">
        <!-- 搜索框 -->
        <el-row>
          <el-col :span="24">
            <div class="results_list_search">
              <div>筛选：</div>
              <el-select
                v-model="checkedLevel"
                placeholder="请选择考试等级"
                size="mini"
                @change="checkedLevelChange"
                :clearable="true"
                style="width: 150px"
              >
                <el-option
                  v-for="item in levelList"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                >
                </el-option>
              </el-select>

              <!-- <el-select
                v-model="checkedExam"
                placeholder="请选择考试科目"
                size="mini"
                @change="checkedExamChange"
                :clearable="true"
                style="width: 200px; margin-left: 10px"
              >
                <el-option
                  v-for="item in checkedExamList"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                >
                </el-option>
              </el-select> -->

              <el-select
                v-model="checkdeAreaId"
                placeholder="请选择考点"
                size="mini"
                style="width: 150px; margin-left: 10px"
                @change="checkedAreaIdChange"
                :clearable="true"
              >
                <el-option
                  v-for="item in areaList"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                >
                </el-option>
              </el-select>

              <el-date-picker
                v-model="checkdeTime"
                type="monthrange"
                size="mini"
                unlink-panels
                range-separator="至"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                style="margin-left: 10px"
                @change="checkedTimeChange"
              >
              </el-date-picker>

              <el-select
                v-model="checkedStatus"
                placeholder="请选择录入状态"
                size="mini"
                @change="checkedStatusChange"
                :clearable="true"
                style="width: 150px; margin-left: 10px"
              >
                <el-option
                  v-for="item in checkedStatusList"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                >
                </el-option>
              </el-select>

              <el-input
                v-model="searchKey"
                placeholder="请输入关键词"
                size="mini"
                style="width: 200px; margin-left: 10px"
              ></el-input>
              <el-button
                type="primary"
                size="mini"
                style="margin-left: 5px"
                @click="searchFn()"
                >搜索</el-button
              >
            </div>
          </el-col>
        </el-row>
        <!-- 按钮 -->
        <el-row>
          <el-col :span="24">
            <div class="results_list_search" style="margin-bottom: 20px">
              <el-button
                type="primary"
                size="mini"
                @click="downloadBtn()"
                :loading="downloadBtnLoading"
                style="width: 110px"
                >{{ downloadBtnText }}</el-button
              >
              <el-upload
                class="upload-demo"
                :action="actionUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
                :name="uploadName"
                style="margin-left: 10px"
              >
                <el-button size="mini" type="primary">导入成绩</el-button>
              </el-upload>
              <el-button
                type="primary"
                size="mini"
                style="margin-left: 10px"
                @click="downloadTemplateFn()"
                >下载模板</el-button
              >
            </div>
          </el-col>
        </el-row>
        <!-- 数据列表 -->
        <el-row
          type="flex"
          justify="center"
          v-if="resultsListData != undefined && resultsListData.length > 0"
        >
          <el-col :span="24">
            <el-table
              :data="resultsListData"
              border
              style="width: 100%"
              size="mini"
              :cell-style="cellStyleFn"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                width="55"
                align="center"
                :selectable="selecTableFn"
              >
              </el-table-column>

              <el-table-column
                prop="level"
                label="考试项目级别"
                align="center"
                width="110"
                :formatter="formatterLevelFn"
              ></el-table-column>

              <el-table-column
                prop="title"
                label="考试项目"
                min-width="200"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="exam_area"
                label="考点"
                width="140"
                align="center"
              ></el-table-column>

              <el-table-column label="考试时间" align="center" width="200">
                <template slot-scope="scope">
                  {{ scope.row.exam_date + " " + scope.row.exam_start_time }}
                </template>
              </el-table-column>

              <el-table-column
                prop="stu_name"
                label="考生名称"
                width="140"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="exam_stu_number"
                label="准考证号"
                width="180"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="score"
                label="分数"
                width="100"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="pass_status"
                label="通过状态"
                width="150"
                align="center"
                :formatter="formatterStatusFn"
              ></el-table-column>

              <el-table-column
                label="操作"
                width="200"
                itemprop=""
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="detailFn(scope.$index, scope.row)"
                    :disabled="scope.row.pass_status == 1"
                    >证书</el-button
                  >
                  <el-button
                    size="mini"
                    type="primary"
                    @click="entryBtn(scope.$index, scope.row)"
                    >录入</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row
          type="flex"
          justify="center"
          v-if="resultsListData != undefined && resultsListData.length > 0"
        >
          <el-col :span="24">
            <div class="results_list_pagination">
              <el-pagination
                @size-change="listSizeChange"
                @current-change="listCurrentChange"
                :current-page="currentPage"
                :page-sizes="pageSizes"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
              >
              </el-pagination>
            </div>
          </el-col>
        </el-row>
        <el-row v-else>
          <el-empty description="暂无成绩"></el-empty>
        </el-row>
      </div>
    </el-row>
    <!-- 录入弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="dialogClose"
    >
      <el-row>
        <el-col :span="24">
          <el-form
            ref="submitFrom"
            :model="submitData"
            label-width="100px"
            :rules="rules"
          >
            <el-form-item label="考生姓名" size="small">
              <el-col :span="24">
                <el-input v-model="submitData.stu_name" disabled></el-input>
              </el-col>
            </el-form-item>

            <el-form-item label="准考证号" size="small">
              <el-col :span="24">
                <el-input
                  v-model="submitData.exam_stu_number"
                  disabled
                ></el-input>
              </el-col>
            </el-form-item>

            <el-form-item label="分数" size="small" prop="score">
              <el-col :span="24">
                <el-input
                  type="number"
                  v-model="submitData.score"
                  maxlength="4"
                ></el-input>
              </el-col>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <el-row type="flex" justify="center">
        <el-col :span="24">
          <div class="results_list_dialog_btn_box">
            <el-button
              size="small"
              type="primary"
              @click="dialogSubmitBtn()"
              style="margin-right: 30px"
              >确认</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="cancelEntryBtn()"
              style="margin-right: 30px"
              >重置</el-button
            >
            <el-button size="small" type="danger" @click="dialogClose()"
              >取消</el-button
            >
          </div>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 证书展示 -->
    <!-- 二维码弹窗 -->
    <el-dialog
      title="证书"
      :visible.sync="certificateDialogVisible"
      :before-close="dialogClose"
      width="500px"
    >
      <div class="results_list_certificate_box">
        <img
          class="results_list_certificate_img"
          :src="baseAPIUrl + certificateImgUrl"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="dialogClose()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<style src="../../assets/css/results/resultsList.css" scoped></style>

<script>
import { saveAs } from "file-saver";
import JSZip from "jszip";

export default {
  name: "ResultsList",
  components: {},
  data() {
    return {
      baseAPIUrl: this.$store.state.baseAPIUrl, //默认路径
      actionUrl: this.$store.state.baseAPIUrl + "/admin/excel/importExamScore", // 上传路径
      uploadName: "excelfile",
      imageShowUrl: "", // 预览路径
      uploadData: {
        source: 2,
      }, // 上传额外参数
      headers: {
        Authorization: this.$store.state.loginToken,
      }, // 上传用token
      resultsListData: [], // 报名列表数据
      currentPage: 1, // 当前页
      pageSizes: [10, 20, 50, 100], // 可选页容量
      pageSize: 10, // 当前页容量
      total: 0, // 总条数
      searchKey: "", // 搜索关键字
      checkedLevel: "", // 等级筛选
      checkedExam: "", // 考试筛选
      checkedStatus: "", // 录入状态筛选
      statusList: [
        {
          key: 1,
          value: "不合格",
        },
        {
          key: 2,
          value: "合格",
        },
        {
          key: 3,
          value: "良好",
        },
        {
          key: 4,
          value: "优秀",
        },
      ], // 状态列表
      checkedStatusList: [
        {
          key: 1,
          value: "未录入",
        },
        {
          key: 2,
          value: "已录入",
        },
      ], // 录入状态筛选下拉
      checkedExamList: [], // 科目筛选下拉
      levelList: [], // 等级列表
      dialogTitle: "成绩录入", // 弹框标题
      dialogVisible: false, // 弹窗显示
      dialogEditId: "", // 编辑id
      dialogEditKey: 0, // 是否编辑
      submitData: {
        id: "",
        stu_name: "",
        exam_stu_number: "",
        score: "",
        certificate: "",
        level: 0,
      }, // 弹框提交数据
      rules: {
        score: [{ required: true, message: "请输入分数", trigger: "blur" }],
        // certificate: [
        //   { required: true, message: "请上传证书照片", trigger: "change" },
        // ],
      }, // 校验规则
      certificateDialogVisible: false, // 证书显示
      certificateImgUrl: "", // 证书显示路径
      multipleSelection: [], // 已勾选列表
      loadingKey: false,
      loadingText: "",
      checkdeAreaId: "", // 筛选--考点
      areaList: [], // 考点列表
      checkdeTime: "", // 筛选--日期
      downloadBtnText: "批量下载证书",
      downloadBtnLoading: false,
      downloadMax: 0,
      downloadNow: 0,
    };
  },
  created: function () {
    this.getlevelListFn();
    // this.getCheckedExamListFn();
    this.getAreaListFn();
    this.getListDataFn();
  },
  methods: {
    // 上传成功钩子
    handleAvatarSuccess: function (res) {
      if (res.code == 1) {
        this.$message.error(res.msg);
      } else {
        this.$message.success("导入成功");
      }
      this.getListDataFn();
    },
    // 上传前钩子
    beforeAvatarUpload: function (file) {
      let type = file.name.indexOf(".xlsx");
      if (type == -1) {
        this.$message.error("上传xlsx文件");
        return false;
      }
      return true;
    },
    // 关闭弹窗
    dialogClose: function () {
      this.dialogVisible = false;
      this.certificateDialogVisible = false;
    },
    // 获取考试科目列表数据
    getCheckedExamListFn: function () {
      let that = this;
      let url = "/admin/exam/examQueryCondition";
      let data = {};
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            let list = [];
            response.exam_list.forEach(function (item) {
              let obj = {
                key: item.id,
                value: item.title,
              };
              list.push(obj);
            });
            that.checkedExamList = list;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 获取等级列表数据
    getlevelListFn: function () {
      let that = this;
      let url = "/mobile/levelText";
      let data = {};
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            let list = [
              {
                key: 0,
                value: "无",
              },
            ];
            response.level_list.forEach(function (item) {
              let obj = {
                key: item.level,
                value: item.title,
              };
              list.push(obj);
            });
            that.levelList = list;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 搜索按钮
    searchFn: function () {
      this.currentPage = 1;
      this.getListDataFn();
    },
    // 考点筛选
    checkedAreaIdChange: function (val) {
      this.checkdeAreaId = val;
    },
    // 时间筛选
    checkedTimeChange: function (val) {
      this.checkdeTime = val;
    },
    // 等级筛选
    checkedLevelChange: function (val) {
      this.checkedLevel = val;
    },
    // 考试筛选
    checkedExamChange: function (val) {
      this.checkedExam = val;
    },
    // 录入状态筛选
    checkedStatusChange: function (val) {
      this.checkedStatus = val;
    },
    // 获取考点列表数据
    getAreaListFn: function () {
      let that = this;
      let url = "/admin/area/index";
      let data = {};
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            let list = [];
            response.area_list.forEach(function (item) {
              let obj = {
                key: item.id,
                value: item.area,
              };
              list.push(obj);
            });
            that.areaList = list;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 查询列表数据
    getListDataFn: function () {
      let that = this;
      let url = "/admin/score/index";
      let data = {
        keywords: this.searchKey,
        page: this.currentPage,
        perPage: this.pageSize,
        level: this.checkedLevel,
        exam_id: this.checkedExam,
        status: this.checkedStatus,
        area_id: this.checkdeAreaId,
      };

      if (this.checkdeTime != null && this.checkdeTime != "") {
        data.exam_date_start = Date.parse(this.checkdeTime[0]) / 1000;
        data.exam_date_end = Date.parse(this.checkdeTime[1]) / 1000;
      }

      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.resultsListData = response.list;
            that.total = response.total_count;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 设置单元格字体颜色
    cellStyleFn: function ({ row, columnIndex }) {
      let style = "";
      if (columnIndex == 8) {
        if (row.pass_status == 1) {
          style = "color: #F6705E";
        } else {
          style = "color: #8ECF5F";
        }
      }
      return style;
    },
    // 状态格式化
    formatterStatusFn: function (row) {
      let status = row.pass_status;
      let key = row.status;
      let text = "";
      if (key == 1) {
        text = "未录入";
      } else {
        this.statusList.forEach(function (item) {
          if (item.key == status) {
            text = item.value;
          }
        });
      }
      return text;
    },
    // 页容量改变
    listSizeChange: function (val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.getListDataFn();
    },
    // 当前页改变
    listCurrentChange: function (val) {
      this.currentPage = val;
      this.getListDataFn();
    },
    // 考试等级格式化
    formatterLevelFn: function (row) {
      let level = row.level;
      let text = "";
      this.levelList.forEach(function (item) {
        if (item.key == level) {
          text = item.value;
        }
      });
      return text;
    },
    // 录入成绩
    entryBtn: function (index, row) {
      this.submitData = {
        id: row.id,
        stu_name: row.stu_name,
        exam_stu_number: row.exam_stu_number,
        score: row.score,
        certificate: "",
        level: row.level,
      };
      this.$nextTick(function () {
        this.dialogVisible = true;
      });
    },
    // 弹窗提交按钮
    dialogSubmitBtn: function () {
      let that = this;
      let url = "";
      let data = {};
      url = "/admin/score/entry";
      data = {
        id: this.submitData.id,
        score: this.submitData.score,
        certificate: this.submitData.certificate,
        level: this.submitData.level,
      };
      that.loadingText = "处理中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.$message.success("录入成功");
            that.dialogClose();
            that.getListDataFn();
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 弹窗重置按钮
    cancelEntryBtn: function () {
      let that = this;
      let url = "";
      let data = {};
      url = "/admin/score/cancelEntry";
      data = {
        id: this.submitData.id,
      };
      that.loadingText = "处理中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.$message.success("重置成功");
            that.dialogClose();
            that.getListDataFn();
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 证书
    detailFn: function (index, row) {
      this.certificateImgUrl = row.certificate;
      this.$nextTick(function () {
        this.certificateDialogVisible = true;
      });
    },
    // 勾选改变
    handleSelectionChange: function (val) {
      this.multipleSelection = val;
    },
    // 设置是否能勾选
    selecTableFn: function (row) {
      if (
        row.pass_status != 1 &&
        row.certificate_print != null &&
        row.certificate_print != "" &&
        row.certificate_print != undefined
      ) {
        return true;
      } else {
        return false;
      }
    },
    // 下载
    downloadFileFn: function (url) {
      return new Promise((resolve, reject) => {
        fetch(url)
          .then((res) => res.blob())
          .then((blob) => {
            resolve(blob);
          })
          .catch((error) => {
            reject(error.toString());
          });
      });
    },

    // 下载按钮
    downloadBtn: function () {
      let that = this;
      let upList = [];
      const zip = new JSZip();
      const promises = [];
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(function (item) {
          if (
            item.certificate_print != null &&
            item.certificate_print != "" &&
            item.certificate_print != undefined
          ) {
            let name = item.stu_name + item.exam_stu_number + ".png";
            upList.push(item);
            const promise = that
              .downloadFileFn(that.baseAPIUrl + item.certificate_print)
              .then((data) => {
                let cil = 0;
                that.downloadNow++;
                cil = Math.floor((that.downloadNow / that.downloadMax) * 100);
                that.downloadBtnText = "下载中 " + cil + "%";
                zip.file(name, data);
              });
            promises.push(promise);
          }
        });
        this.downloadBtnLoading = true;
        this.downloadBtnText = "下载中...";
        this.downloadMax = upList.length;
        this.downloadNow = 0;
        Promise.all(promises).then(() => {
          zip
            .generateAsync({
              type: "blob",
            })
            .then((content) => {
              saveAs(content, "证书.zip");
              this.downloadBtnLoading = false;
              this.downloadBtnText = "批量下载证书";
            });
        });
      }
    },
    // 下载模板
    downloadTemplateFn: function () {
      const link = document.createElement("a");
      // 这里是将链接地址url转成blob地址，
      fetch(this.baseAPIUrl + "/download/import_exam_score.xlsx")
        .then((res) => res.blob())
        .then((blob) => {
          link.href = URL.createObjectURL(blob);
          // 下载文件的名称及文件类型后缀
          link.download = "import_exam_score.xlsx";
          document.body.appendChild(link);
          link.click();
          // 在资源下载完成后 清除 占用的缓存资源
          window.URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        });
    },
  },
};
</script>
